<template>
  <div>
    <el-dialog
      title="添加用户"
      :visible.sync="isVisible"
      :show-close="false"
      width="50%">
      <el-form ref="addFormRef" :model="addForm" label-width="80px"  :rules="addFormRules">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="电话">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleCommit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AddDialog',
  props: ['isVisible'],
  data() {
    const checkEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('电子邮箱不能为空'));
        }
        const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/i
        if (!emailReg.test(value)) {
          return callback(new Error('请输入合法的电子邮箱'));
        }
        callback()
      };
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('电话不能为空'));
      }
      const mobileReg = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/i
      if (!mobileReg.test(value)) {
        return callback(new Error('请输入合法的电话号码'));
      }
      callback()
    };
    return {
      addForm: {
        username: '',
        mobile: '',
        email: '',
        password: ''
      },
      addFormRules: {
        username: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    handleCancel() {
      this.$emit('cancel')
    },
    handleCommit() {
      // 参数校验
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.$emit('commit', this.addForm, this.$refs.addFormRef)
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>